#!/usr/bin/env python
# _*_ coding: utf-8 _*_
#
#
# Copyright (C) 2020 Wei Keting<weikting@gmail.com>. All rights reserved.
# @Time : 2020-09-10 16:59 
# @File : utils.py.py
# @Description :
#
#

import tensorflow as tf
import re


def tf_version(v: str):
    """
    check running tensorflow's version
   :param v:version to compare
    :return:true running version is greater then v
    """
    vv = tf.__version__
    vv = re.sub("[-_].*[0-9]", "", vv)
    v0 = vv.split('.')
    v1 = v.split('.')
    l = min(len(v0), len(v1))
    if l == 0: return False
    ret = True
    for i in range(l):
        if int(v0[i]) < int(v1[i]):
            ret = False
            break
    return ret


def fix_tf_cudnn_error():
    if tf_version('2.0.0'):
        physical_devices = tf.config.list_physical_devices('GPU')
        for p in physical_devices:
            tf.config.experimental.set_memory_growth(p, True)
    else:
        config = tf.ConfigProto(allow_soft_placement=True)  # ,log_device_placement = True)
        config.gpu_options.allow_growth = True
        sess = tf.Session(config=config)
        tf.keras.backend.set_session(sess)
    tf.keras.backend.set_learning_phase(1)


def tf_variable_value(var):
    return tf.keras.backend.get_value(var)
